import { Component, OnInit } from '@angular/core';
import { EnvironmentService } from 'src/app/core/service/environment.service';

@Component({
  selector: 'app-env-list',
  templateUrl: './env-list.component.html',
  styleUrls: ['./env-list.component.scss']
})
export class EnvListComponent implements OnInit {
  maxShowNum = 2;  // 最多显示的数量
  isHidden = true; // 默认隐藏
  allChecked = false;
  indeterminate = false;
  displayData = [];

  filter: string;

  // 表格显示样式（页码、每页显示多少页、总共几页、获取到的数据）
  pageIndex = 1;      // 页码标识
  pageSize = 10;      // 每页展示多少数据 —— 10条
  total = 1;          // 总共1页
  dataSet = [];       // 数据集合
  loading = true;     // 加载
  sortValue = null;   // 种类值
  sortKey = null;     // 种类关键值
  constructor(
    private environmentService: EnvironmentService
  ) { }

  /**
   * (nzSortChange)="sort($event)"
   * @param sort 数据搜索
   */
  sort(sort: { key: string, value: string }): void {
    this.sortKey = sort.key;
    this.sortValue = sort.value;
    console.log(`${this.sortKey}-${this.sortValue}`);
    // this.getLibPage();
  }

  getEnvsPage(reset: boolean = false): void {
    if (reset) {
      this.pageIndex = 1;
    }
    this.environmentService.getEnvsPage(this.pageIndex, this.pageSize, this.filter)
      .subscribe((CVEPage) => {
        console.log(`===收到json数据===> ${CVEPage}`);
        this.loading = false; // 获取到数据之后，不再显示加载图标
        this.total = CVEPage.total;   // 数据的条数
        this.dataSet = CVEPage.data;        // 数据集
        console.log('===CVEPage现在的数据===', CVEPage.data);
      });
  }

  currentPageDataChange($event: Array<{ name: string; age: number; address: string; checked: boolean; disabled: boolean; }>): void {
    this.displayData = $event;
    this.refreshStatus();
  }

  /**
   * 刷新状态
   */
  refreshStatus(): void {
    const allChecked = this.displayData.filter(value => !value.disabled).every(value => value.checked === true);
    const allUnChecked = this.displayData.filter(value => !value.disabled).every(value => !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  /**
   * 全选方法
   */
  checkAll(value: boolean): void {
    this.displayData.forEach(data => {
      if (!data.disabled) {
        data.checked = value;
      }
    });
    // 刷新状态
    this.refreshStatus();
  }

  ngOnInit(): void {
    this.getEnvsPage();
  }
}
